package com.niiwoo.civet.trade.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.constant.MqConstant;
import com.niiwoo.civet.trade.dao.entity.CreditorSaleDetail;
import com.niiwoo.civet.trade.service.local.creditor.CreditorTransferConfirmLocalService;
import com.niiwoo.tripod.provider.exception.BizException;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class CreditorTransferListener {

    private static final Logger logger = LoggerFactory.getLogger(CreditorTransferListener.class);

    @Autowired
    private CreditorTransferConfirmLocalService creditorTransferConfirmLocalService;

    @RabbitListener(queues = {MqConstant.CREDITOR_TRANSFER_PROTOCOL_SIGN_QUEUE})
    public void projectLendContractHandler(CreditorSaleDetail creditorSaleDetail, Message message, Channel channel) throws IOException {
        //应答标记
        Boolean isAck = true;
        try {
            logger.info("creditorTransferProtocolSign creditorSaleDetail:{}", JSON.toJSON(creditorSaleDetail));
            creditorTransferConfirmLocalService.creditorTransferProtocol(creditorSaleDetail);
        } catch (BizException e) {
            logger.error("creditorTransferProtocolSignBizException", e);
        } catch (Exception e) {
            logger.error("creditorTransferProtocolSignException", e);
            isAck = false;
            try {
                Thread.sleep(5 * 1000);
            } catch (Exception expect) {
            }
        } finally {
            if (isAck) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }
}
